package conn

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"gitee.com/ander888/tools/model"
	clientv3 "go.etcd.io/etcd/client/v3"
)

type EtcdClient struct {
	Conf model.EtcdConf
	Conn *clientv3.Client
	Err  error
}

// NewEtcdClient 创建etcd的客户端
func (e *EtcdClient) NewEtcdClient() {
	e.Conn, e.Err = clientv3.New(clientv3.Config{
		Endpoints:   e.Conf.Nodes,
		DialTimeout: 5 * time.Second,
		Username:    e.Conf.User,
		Password:    e.Conf.Pwd,
	})
}

// Parse 解析etcd内的value
func (e *EtcdClient) Parse(key string, v interface{}) error {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	result, err := e.Conn.Get(ctx, key)
	if err != nil {
		return err
	}
	if result == nil || len(result.Kvs) == 0 {
		return fmt.Errorf("no more config value,the key is %s, value is %v", key, result)
	}
	return json.Unmarshal(result.Kvs[0].Value, v)
}

/*
etcd 键入key value  创建你的数据

	data := YourData{
		Field1: "Value1",
		Field2: 42,
		// Initialize other fields as needed
	}
*/
func (e *EtcdClient) Put(key string, data interface{}) error {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	// 将数据编码为JSON
	jsonData, err := json.Marshal(data)
	if err != nil {
		fmt.Println("Failed to marshal JSON:", err)
		return err
	}
	_, err = e.Conn.Put(ctx, key, string(jsonData))
	return err
}

// Close 关闭etcd的连接
func (e *EtcdClient) Close() {
	_ = e.Conn.Close()
}
